import { createContext, useContext, useEffect, useState } from 'react';
import { shallowEqual, useSelector } from 'react-redux';
import { useMainContext } from '@/layouts/main-context';
import { IRootReducerState } from '@/store/root-reducer';
import { initialQuery } from './helper';

const PageContext = createContext<any>(null);
export function usePageContext() {
  return useContext(PageContext);
}
export const RoleConsumer = PageContext.Consumer;

const RoleProvider = ({ PageEvents, children }: any) => {
  const loading = useSelector<IRootReducerState, any>(
    (state) => state.role.loading,
    shallowEqual
  );

  const MainContext = useMainContext();
  useEffect(() => {
    MainContext.setLoading(loading);
  }, [loading]);
  useEffect(() => {
    return () => MainContext.setLoading(false);
  }, []);

  const [showSider, setShowSider] = useState(false);
  const [showFloater, setShowFloater] = useState(false);
  const [queryParams, setQueryParams] = useState(initialQuery);

  const value = {
    showSider,
    setShowSider,
    showFloater,
    setShowFloater,
    queryParams,
    setQueryParams,
    addRecord: PageEvents.addRecord,
    editRecord: PageEvents.editRecord,
    delRecord: PageEvents.delRecord,
    detailRecord: PageEvents.detailRecord,
    appRecord: PageEvents.appRecord,
  };

  return <PageContext.Provider value={value}>{children}</PageContext.Provider>;
};

export default RoleProvider;
